package queue;

import entity.StudentDTO;
import entity.student;

import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList();

        student s1 = new student(null, null, 3, 281,"28号1点");
        student s2 = new student(null, null, 2, 282,"28号2点");
        student s3 = new student(null, null, 3, 283,"28号3点");
        student s4 = new student(null, null, 9, 284,"28号4点");
        student s5 = new student(null, null, 6, 285,"28号5点");
        student s6 = new student(null, null, 7, 286,"28号6点");

        List<student> students = new ArrayList<>();
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);
        students.add(s5);
        students.add(s6);

        List<String> matchSuccess = Main.getMatchSuccess(students, 12);
        System.out.println(matchSuccess);
        System.out.println(students);

        List<student> collect = students.stream().sorted(Comparator.comparingInt(student::getAge)).collect(Collectors.toList());
        System.out.println(collect);
        List<String> matchSuccess1 = Main.getMatchSuccess(collect, 12);
        System.out.println(matchSuccess1);

    }

    public static List<String> getMatchSuccess(List<student> students, Integer result) {

        // 返回订单id
        List<String> resultOrderIds = new ArrayList<>();

        // 建立一个空队列
        Queue<student> queue = new LinkedList();
        // 初始价格为0
        Integer price = 0;
        boolean next = true;
        for (int i = 0; i < students.size()-1; i++) {

            if (price.equals(result)) {
                // 价格相等 停止循环
                break;
            }
            if (price < result && next) {
                // 价格不够入队 加钱
                queue.offer(students.get(i));
                price = price + students.get(i).getAge();
            }
            if (price > result) {
                // 价格超了出队 减钱
                entity.student poll = queue.poll();
                price = price - poll.getAge(); // 到下一次处理应该仍旧处理当前
                i--;
                next = false;
                // 存在问题 出队列 减钱了 但是到处理下一个并没有入队 导致下一个就没处理 跳过了
            } else {
                next = true;
            }

        }
        if (price.equals(result)) {
            // 现在队列里为匹配上的订单ids
            while (!queue.isEmpty()) {
                resultOrderIds.add(queue.poll().getDay());
            }
        }
        // 返回订单这些ids
        return resultOrderIds;

    }



}
